import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vc_package/mvvm/base/provider_widget.dart';
import 'base_view_model_bus_event.dart';

enum ViewState {
  idle,
  busy, //加载中
  empty, //无数据
  error, //加载失败
}

class BaseViewModel with ChangeNotifier {
  late bool _disposed = false;
  late ViewState _viewState;
  BuildContext? context;
  late bool autoLoadData;

  BaseViewModel({ViewState? viewState, BuildContext? context})
      : _viewState = (viewState ?? ViewState.idle),
        context = context {
    debugPrint('BaseViewModel---constructor--->$runtimeType');

    BaseViewModelBusEvent?.handleFunction(
        viewModel: '$runtimeType',
        type: BaseViewModelBusEvent.BASE_VIEW_MODEL_PUSH);
  }

  /// ViewState
  ViewState get viewState => _viewState;

  setBuildContext(BuildContext context) {
    this.context = context;
  }

  set viewState(ViewState viewState) {
//    _viewStateError = null;
    _viewState = viewState;
    notifyListeners();
  }

  bool get isBusy => viewState == ViewState.busy;

  bool get isIdle => viewState == ViewState.idle;

  bool get isEmpty => viewState == ViewState.empty;

  bool get isError => viewState == ViewState.error;

  void setIdle() {
    viewState = ViewState.idle;
  }

  void setBusy() {
    viewState = ViewState.busy;
  }

  void setEmpty() {
    viewState = ViewState.empty;
  }

  @override
  void notifyListeners() {
    if (!_disposed) {
      super.notifyListeners();
    }
  }

  @override
  void dispose() {
    _disposed = true;
    debugPrint('BaseViewModel dispose -->$runtimeType');

    BaseViewModelBusEvent?.handleFunction(
        viewModel: '$runtimeType',
        type: BaseViewModelBusEvent.BASE_VIEW_MODEL_POP);
    super.dispose();
  }

  ///初始化
  void initState() {}

  /// 显示时的回调，应用从后台调度到前台时
  void onShow() {
    print('---onShow');
  }

  /// 隐藏时的回调
  void onHide() {
    print('---onHide');
  }

  /// 可见，并且可以响应用户操作时的回调
  /// 比如应用从后台调度到前台时，在 onShow() 后面 执行
  /// 注意：这个回调，初始化时 不执行
  void onResume() {
    print('---onResume');
  }

  /// 可见，但无法响应用户操作时的回调
  void onInactive() {
    print('---onInactive');
  }

  /// 暂停时的回调
  void onPause() {
    print('---onPause');
  }

  /// 这两个回调，不是所有平台都支持，

  /// 当退出 并将所有视图与引擎分离时的回调（IOS 支持，Android 不支持）
  void onDetach() {
    print('---onDetach');
  }

  /// 暂停后恢复时的回调
  void onRestart() {
    print('---onRestart');
  }

  /// 监听状态
  void onStateChange(AppLifecycleState state) {
    print('app_state：$state');
  }

  /// 在退出程序时，发出询问的回调（IOS、Android 都不支持）
  /// 响应 [AppExitResponse.exit] 将继续终止，响应 [AppExitResponse.cancel] 将取消终止。
  Future<AppExitResponse> onExitRequested() async {
    print('---onExitRequested');
    return AppExitResponse.exit;
  }

  ///页面即将显示时调用
  void viewWillAppear(RouteChangeType type) {
    print('---viewWillAppear');
  }
}